import { authorizationsPost, smsCodes } from '@/api'
import { LoginForm, Token } from '@/types/data'
import { LoginAction, RootThunkAction } from '@/types/store'
import { removeToken, setToken } from '@/utils/auth'
// 设置token的action
function saveToken (token: Token): LoginAction {
  setToken(token)
  return { type: 'login/login', payload: token }
}
// 登录的 action
function loginAction (data: LoginForm): RootThunkAction {
  return async dispatch => {
    const res = await authorizationsPost(data)
    // console.log(res)
    dispatch(saveToken(res.data.data))
  }
}
// 发送验证码
function codeAction (mobile: string): RootThunkAction {
  return async () => {
    await smsCodes(mobile)
    // console.log(res)
  }
}
// 同步登出
function logout (): LoginAction {
  removeToken()
  return { type: 'user/logout' }
}
// 登出异步
function logoutAction (): RootThunkAction {
  return dispatch => {
    dispatch(logout())
  }
}
export { loginAction, codeAction, logoutAction, logout, saveToken }
